package org.j2meturk.main;

/***
 * 
 * Copyright (C) 2008 Alessandro La Rosa
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Contact: alessandro.larosa@gmail.com
 *
 * Author: Alessandro La Rosa
 */

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

public class ReflectedImage
{
	public static Image create(Image image, int bgColor, int reflectionHeight)
	{
		int w = image.getWidth();
		int h = image.getHeight();
		
		Image reflectedImage = Image.createImage(w, h + reflectionHeight);
		
		Graphics g = reflectedImage.getGraphics();
		
		g.setColor(bgColor);
		g.fillRect(0, 0, w, h + reflectionHeight);
		
		g.drawImage(image, 0, 0, Graphics.TOP | Graphics.LEFT);
		
		int[] rgba = new int[w];
		int currentY = -1;
		
		for(int i = 0; i < reflectionHeight; i++)
		{
			int y = (h - 1) - (i * h / reflectionHeight);
			
			if(y != currentY)
				image.getRGB(rgba, 0, w, 0, y, w, 1);
			
			int alpha = 0xff - (i * 0xff / reflectionHeight);
			
			for(int j = 0; j < w; j++)
			{
				int origAlpha = (rgba[j] >> 24);
				int newAlpha = (alpha & origAlpha) * alpha / 0xff;

				rgba[j] = (rgba[j] & 0x00ffffff);
				rgba[j] = (rgba[j] | (newAlpha << 24));
			}

			g.drawRGB(rgba, 0, w, 0, h + i, w, 1, true);
		}
		return reflectedImage;
	}
}
